package com.itheima.web;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    @RequestMapping("/setNumberByDate")
    public Result setNumberByDate(@RequestBody OrderSetting orderSetting){
        orderSettingService.setNumberByDate(orderSetting);
        return Result.OK("");
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile){
        try {
            //直接调用poi工具读取excel(data 里面的一个数组里面存的就是excel里面一行数据)
            List<String[]> data = POIUtils.readExcel(excelFile);
            //把data 里面的数组转为OrderSetting对象
            List<OrderSetting> orderSettings = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(data)){
                for (String[] row : data) {
                    //注意：一定要判断
                    if(row.length != 2){
                        continue;
                    }

                    String dateStr = row[0];
                    String numberStr = row[1];
                    //注意：一定要判断
                    if(StrUtil.isNotEmpty(dateStr) && StrUtil.isNotEmpty(numberStr)){
                        DateTime orderDate = DateUtil.parse(dateStr, "yyyy/MM/dd");//日期格式和Excel里面保持一致
                        OrderSetting orderSetting = new OrderSetting(orderDate, Integer.valueOf(numberStr));
                        orderSettings.add(orderSetting);
                    }
                }
            }
            //执行批量插入
            orderSettingService.setNumberByDateBatch(orderSettings);
            return Result.OK("");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.ERROR("批量导入失败");
        }
    }

    @RequestMapping("/findByMonth")
    public Result findByMonth(String month){
        // [{"date":22,"mouth":3,"number":300,"reservations":300,}] 返回的数据格式
        List<Map> maps = orderSettingService.findByMonth(month);
        return Result.OK("",maps);
    }

}
